本人需要判断一个字符串里括号是否成对出现,发现正则满足不了或者正则表达式太复杂,只能用java算法实现了,网上找了几段代码,发现要么不合适,要么有的情况会误判,无奈只能参考那些例子进行改造了,现在贴出来,希望对某些人有用。
import java.util.HashMap;
import java.util.Map;
import java.util.Stack;
public class matchJudger
{
private Map<Character, Character> pair = null;
public matchJudger()
{
pair = new HashMap<Character, Character>();
pair.put(')', '(');
pair.put('}', '{');
pair.put(']', '[');
}
public boolean isMatch(String s)
{
Stack<Character> sc = new Stack<Character>();
for (int i = 0; i < s.length(); i++)
{
Character ch = s.charAt(i);
if (pair.containsValue(ch))
{
sc.push(ch);
} else if (pair.containsKey(ch))
{
if (sc.empty())
{
return false;
}
if (sc.peek() == pair.get(ch))
{
sc.pop();
} else
{
return false;
}
}
}
return sc.empty() ? true : false;
}
public static void main(String[] args)
{
matchJudger judger = new matchJudger();
System.out.println(judger.isMatch("(***)-[{-------}]"));
System.out.println(judger.isMatch("(2+4)*a[5]"));
System.out.println(judger.isMatch("({}[]]])"));
System.out.println(judger.isMatch("())))"));
}
}